<template>
  <div class="quotation-page">
    <div class="toolbar">
      <div class="left">
        <button class="btn primary" @click="showCreate = true">新建</button>
      </div>
      <div class="right">
        <span class="label">关键词</span>
        <input class="input" v-model="query.keyword" placeholder="请输入报价单号/客户名称" />
        <span class="label">状态</span>
        <select class="select" v-model="query.status">
          <option :value="''">全部</option>
          <option :value="1">报价中</option>
          <option :value="0">已成交</option>
          <option :value="2">已拒绝</option>
        </select>
        <button class="btn" @click="onSearch">搜索</button>
        <button class="btn" @click="onReset">重置</button>
        </div>
      </div>

    <div class="table-wrapper">
      <table class="table">
          <thead>
            <tr>
            <th style="width:48px"><input type="checkbox" v-model="checkedAll" @change="toggleAll" /></th>
              <th>报价单号</th>
            <th>客户名称</th>
            <th>联系人</th>
            <th>联系电话</th>
              <th>负责销售</th>
              <th>报价时间</th>
            <th>期望发货</th>
              <th>报价总金额</th>
            <th>状态</th>
            </tr>
          </thead>
          <tbody>
          <tr v-for="item in list" :key="item.quotationId">
            <td><input type="checkbox" v-model="selectedIds" :value="item.quotationId" /></td>
            <td>
              <button class="link" @click="view(item)">{{ item.quotationNo }}</button>
            </td>
            <td>{{ item.customerName }}</td>
            <td>{{ item.contactPersonName || '-' }}</td>
            <td>{{ item.contactPhone || '-' }}</td>
            <td>{{ item.salesPersonName }}</td>
            <td>{{ formatDate(item.quotationDate) }}</td>
            <td>{{ formatDate(item.expectedDeliveryDate) }}</td>
            <td>{{ item.totalAmount }}</td>
            <td>{{ renderStatus(item.status) }}</td>
          </tr>
          <tr v-if="!list || list.length === 0">
            <td colspan="11" class="empty">暂无数据</td>
            </tr>
          </tbody>
        </table>
        <div class="table-footer">
        <div class="footer-left">
          <input type="checkbox" v-model="checkedAll" @change="toggleAll" /> 全选
          <button class="btn">导出</button>
        </div>
        <div class="footer-right">
          <button class="btn" :disabled="page.pageNum===1" @click="changePage(page.pageNum-1)">上一页</button>
          <span>第 {{ page.pageNum }} / {{ totalPages }} 页</span>
          <button class="btn" :disabled="page.pageNum>=totalPages" @click="changePage(page.pageNum+1)">下一页</button>
          <span>{{ page.pageSize }} 条/页</span>
        </div>
      </div>
    </div>

    <div v-if="showCreate" class="modal-mask" @click.self="showCreate=false">
      <div class="modal">
        <h3>新建报价单</h3>
        <div class="form">
          <label>客户ID</label>
          <input v-model.number="form.customerId" type="number" />
          <label>销售用户ID</label>
          <input v-model.number="form.uId" type="number" />
          <label>报价时间</label>
          <input v-model="form.quotationDate" type="datetime-local" />
          <label>期望发货时间</label>
          <input v-model="form.expectedDeliveryDate" type="datetime-local" />
          <label>总金额</label>
          <input v-model.number="form.totalAmount" type="number" step="0.01" />
           </div>
        <div class="actions">
          <button @click="submitCreate">提交</button>
          <button @click="showCreate=false">取消</button>
           </div>
        </div>
    </div>

    <div v-if="showDetail" class="drawer-mask" @click.self="showDetail=false">
      <div class="drawer detail-drawer">
        <h3>{{ detail.quotationNo }} - 报价单详情</h3>

        <div class="card">
          <div class="card-title">基础信息</div>
          <div class="form grid-2">
            <label>报价单号</label>
            <input :value="detail.quotationNo || '-'" disabled />
            <label>审批状态</label>
            <input :value="renderApproval(detail.approvalStatus)" disabled />
            <label>报价时间</label>
            <input :value="formatDate(detail.quotationDate)" disabled />
            <label>备注</label>
            <input :value="detail.remark || '-'" disabled />
          </div>
        </div>

        <div class="card">
          <div class="card-title">对接人信息</div>
          <div class="form grid-2">
            <label>负责销售</label>
            <input :value="detail.salesPersonName || detail.uId || '-'" disabled />
            <label>客户</label>
            <input :value="detail.customerName || detail.customerId || '-'" disabled />
            <label>联系人</label>
            <input :value="detail.contactPersonName || '-'" disabled />
            <label>联系方式</label>
            <input :value="detail.contactPhone || '-'" disabled />
          </div>
        </div>

        <div class="card">
          <div class="card-title">发货信息</div>
          <div class="form grid-2">
            <label>期望发货时间</label>
            <input :value="formatDate(detail.expectedDeliveryDate)" disabled />
            <label>报价状态</label>
            <input :value="renderStatus(detail.status)" disabled />
            <label>总金额</label>
            <input :value="detail.totalAmount || 0" disabled />
            <label>邮件</label>
            <input :value="detail.email || '-'" disabled />
          </div>
        </div>

        <h4>报价明细</h4>
        <ul class="detail-list">
          <li v-for="d in details" :key="d.id">
            明细ID: {{ d.id }} 数量: {{ d.quantity }} 单价: {{ d.unitPrice }} 最终金额: {{ d.finalPrice }}
          </li>
        </ul>
      </div>
    </div>
  </div>

</template>

<script>
import { quotationPage, quotationCreate, quotationDetail, quotationDetailsByQuotation } from '@/api/sale/quotation'

export default {
  name: 'QuotationManagement',
  data() {
    return {
      query: { quotationNo: '', keyword: '', status: '' },
      page: { pageNum: 1, pageSize: 10 },
      list: [],
      total: 0,
      checkedAll: false,
      selectedIds: [],
      showCreate: false,
      form: {
        customerId: null,
        uId: null,
        quotationDate: '',
        expectedDeliveryDate: '',
        totalAmount: 0,
        status: 1,
        approvalStatus: 1
      },
      showDetail: false,
      detail: {},
      details: []
    }
  },
  computed: {
    totalPages() {
      return Math.max(1, Math.ceil(this.total / this.page.pageSize))
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    async fetch() {
      const res = await quotationPage({
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        quotationNo: this.query.quotationNo || this.query.keyword || '',
        status: this.query.status || undefined
      })
      const payload = res?.data || res
      if (payload && (payload.code === 200 || payload.success === true)) {
        const data = payload.data || {}
        this.list = data.records || []
        this.total = data.total || 0
      }
    },
    onSearch() {
      this.page.pageNum = 1
      this.fetch()
    },
    onReset() {
      this.query = { quotationNo: '', keyword: '', status: '' }
      this.page.pageNum = 1
      this.fetch()
    },
    changePage(n) {
      this.page.pageNum = n
      this.fetch()
    },
    toggleAll() {
      if (this.checkedAll) {
        this.selectedIds = (this.list || []).map(i => i.quotationId)
      } else {
        this.selectedIds = []
      }
    },
    renderStatus(s) {
      if (s === 0) return '已成交'
      if (s === 1) return '报价中'
      if (s === 2) return '已拒绝'
      return '-'
    },
    renderApproval(a) {
      if (a === 0) return '未提交'
      if (a === 1) return '待审批'
      if (a === 2) return '审批通过'
      if (a === 3) return '审批拒绝'
      return '-'
    },
    formatDate(d) {
      if (!d) return '-'
      const dt = new Date(d)
      const y = dt.getFullYear()
      const m = String(dt.getMonth() + 1).padStart(2, '0')
      const da = String(dt.getDate()).padStart(2, '0')
      return `${y}-${m}-${da}`
    },
    async submitCreate() {
      const payload = { ...this.form }
      if (payload.quotationDate) payload.quotationDate = new Date(payload.quotationDate)
      if (payload.expectedDeliveryDate) payload.expectedDeliveryDate = new Date(payload.expectedDeliveryDate)
      const res = await quotationCreate(payload)
      const data = res?.data || res
      if (data && (data.code === 200 || data.success === true)) {
        this.showCreate = false
        this.fetch()
      } else {
        alert(data?.message || data?.msg || '创建失败')
      }
    },
    async view(item) {
      this.showDetail = true
      const r1 = await quotationDetail(item.quotationId)
      const p1 = r1?.data || r1
      if (p1 && (p1.code === 200 || p1.success === true)) this.detail = p1.data || {}
      const r2 = await quotationDetailsByQuotation(item.quotationId)
      const p2 = r2?.data || r2
      if (p2 && (p2.code === 200 || p2.success === true)) this.details = p2.data || []
    }
  }
}
</script>

<style scoped>
.toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; background: white}
.toolbar .left { display: flex; gap: 8px; }
.toolbar .right { display: flex; align-items: center; gap: 8px; }
.label { color: #666; }
.input { border: 1px solid #dcdfe6; padding: 6px 8px; border-radius: 4px; width: 220px; }
.select { border: 1px solid #dcdfe6; padding: 6px 8px; border-radius: 4px; }
.btn { border: 1px solid #dcdfe6; background: #fff; padding: 6px 12px; border-radius: 4px; cursor: pointer; }
.btn.primary { background: #409eff; color: #fff; border-color: #409eff; }
.table-wrapper { border: 1px solid #ebeef5; border-radius: 4px; }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { border-bottom: 1px solid #ebeef5; padding: 10px; text-align: left; }
.table thead th { background: #fafafa; color: #606266; font-weight: 500; }
.link { color: #409eff; background: transparent; border: none; cursor: pointer; }
.empty { text-align: center; color: #909399; padding: 20px; }
.table-footer { display: flex; justify-content: space-between; align-items: center; padding: 10px; }
.modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.4); display: flex; align-items: center; justify-content: center; }
.modal { background: #fff; padding: 16px; width: 420px; border-radius: 6px; }
.form { display: grid; grid-template-columns: 100px 1fr; gap: 8px; }
.actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px; }
.drawer-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.2); display: flex; justify-content: flex-end; }
.drawer { background: #fff; width: 520px; padding: 12px; height: 100%; overflow: auto; }
.detail-json { white-space: pre-wrap; background: #fafafa; padding: 8px; border: 1px solid #eee; }
.detail-drawer h3 { margin: 8px 0 12px; }
.card { border: 1px solid #ebeef5; border-radius: 6px; padding: 10px; margin-bottom: 12px; }
.card-title { font-weight: 600; margin-bottom: 8px; }
.grid-2 { display: grid; grid-template-columns: 100px 1fr 100px 1fr; gap: 8px; }
.detail-list { padding-left: 16px; }
</style>

